<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Api\Service\AuthService;
use App\Http\Controllers\Api\Service\LoginService;
use App\Models\AdminUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;

class CommonController extends BaseController
{






    //登录
    public function login(Request $request)
    {
        $data = $request->post();
        $validator = Validator::make($data, [
            'username' => 'required',
            'pass' => 'required',
        ], [
            'username.required' => '用户名必填',
            'pass.required' => '密码必填',
        ]);

        if ($validator->fails()) {
            return error($validator->errors()->first());
        }

        $result = LoginService::login($data);

        if (!$result) {
            return error();
        }
        return success($result);

        // 登录
        AdminUsers::login();

        return AdminUsers::find(1);
    }



    //退出登录
    public function loginOut(Request $request)
    {

        $userInfo=LoginService::getUserInfo($request);
        LoginService::removeToken($userInfo['info']['id']);
        return success();
    }




    public function download(Request $request)
    {
        $data = $request->all();
        $fields = [
            'url' => 'required',
        ];
        $validator = Validator::make($data, $fields);
        if ($validator->fails()) {
            return error($validator->errors()->first());
        }
        $url = $data['url'];
        $filename = md5($url) . '.png';
        $headers = get_headers($url, 1);
        $fileSize = $headers['Content-Length'];
        header('Content-Type: application/octet-stream');
        header('Access-Control-Allow-Origin: *');
        header('Accept-Ranges:bytes');
        header('Content-Length: ' . $fileSize);
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        readfile($url);
        die;
    }



    //获取后台用户信息
    public function getUserInfo(Request $request)
    {
        $data=LoginService::getUserInfo($request);
        return success($data);
    }



}
